<?php

namespace App\Repository\XhApi;

use App\Libs\PhoneArea;
use App\Libs\PhpOffice\Excel;
use App\Models\DictConfig;
use App\Models\Order\OrderMoreModel;
use App\Models\Xh\PhonesModel;
use App\Repository\BaseRepository;

class PhonesRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new PhonesModel();
        parent::__construct();
    }

    public function index($params, $page = 1, $limit = 10)
    {
        $where = [];
        if (!empty($params['number'])) {
            $where['where']['number'] = $params['number'];
        }
        if (!empty($params['shop_id'])) {
            $where['where']['shop_id'] = $params['shop_id'];
        }
        if (isset($params['status']) && $params['status'] != '') {
            $where['where']['status'] = (int)$params['status'];
        }
        if (!empty($params['dateRange'])) {
            $time = $params['dateRange'];
            $where['between']['created_at'] = $time;
        }
        //        先要总数
        $totalRows = 0;
        if ($page == 1) {
            $totalRows = $this->model->searchWhere($where)->count('id');
        }
        $rows = $this->model->searchWhere($where)->page($page, $limit)->orderByDesc('id')->get();
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

    public function del($id, $shopId = 0)
    {
//        可以多选的情况
        $ids = explode(',', $id);
        $where = [];
        if ($shopId != SUPPER_SHOP_ID) {
            $where['shop_id'] = $shopId;
        }
        if (count($ids) === 1) {
            $where['eq']['id'] = $ids[0];
        } else {
            $where['in']['id'] = $ids;
        }
        $this->model->searchWhere($where)->delete();
        return $this->returnMsg(200, '删除操作完成');
    }

//把号码分成每个数字
    public function splitNumber($number)
    {
        $number = trim($number);
        $arr = [];
        for ($i = 0; $i <= 10; $i++) {
            $arr['t' . $i] = $number[$i];
        }
        return $arr;
    }

    public function edit($postData)
    {
        return $this->addAndEdit($postData);
    }

    public function add($postData)
    {
        return $this->addAndEdit($postData);
    }

    public function addAndEdit($postData)
    {
        if (empty($postData['user'])) {
            return $this->returnMsg(2, '帐号信息异常');
        }
        $loginUsersId = $postData['user']['id'];
        $loginUsersShopId = $postData['user']['shop_id'];
//        必填写字段
        $mustFields = [
            "number" => '号码必填写',
            "goods_id" => '商品必填写'
        ];
//        接受的字段
        $optionalFields = [
            'id',
            'raw_price',
            'is_top',
            'is_pretty',
            'booking',
            'status'
        ];
        $inData = $this->getRealData($postData, array_keys($mustFields), $optionalFields, $mustFields);
        if (empty($inData) || is_string($inData)) {
            return $this->returnMsg(
                2,
                $inData
            );
        }

        $inData['created_by'] = $loginUsersId;
        $inData['shop_id'] = $loginUsersShopId;
        $operatorType = config('card.operatorType');
        $operatorFlag = config('card.operatorFlag');
        $numbers = preg_split('/[;\r\n]+/s', $inData['number']);
        $numbers = array_filter($numbers);
//        var_dump($numbers);
        $ModelDictConfig = new DictConfig();
        $incPriceSetting = $ModelDictConfig->getValue('xhPriceInc');
        //取后8位数据,相同的就是情侣号
        $groupNumberEnd8 = [];
        $PhoneArea = new PhoneArea();
        if (isset($inData['id']) && $inData['id'] > 0) {
//            编辑,只有一个号码
            $id = $inData['id'];
            unset($inData['id']);
            $inData['number'] = trim($numbers[0]);
            $area = $PhoneArea->find($inData['number']);
            $inData['province'] = $area['province'] ?? '';
            $inData['city'] = $area['city'] ?? '';
            $inData['operator'] = $this->getOperatorName($inData['number'], $operatorType, $operatorFlag);
            $groupNumberEnd8[] = substr($inData['number'], 3);
            // 加价设置
            $prices = $this->getIncPrice($inData['raw_price'], $incPriceSetting);
            $inData['sale_price'] = $prices['sale_price'];
            $inData['agent_price'] = $prices['agent_price'];
            $inData = array_merge($inData, $this->splitNumber($inData['number']));
            $this->model->where(['id' => $id])->update($inData);
        } else {
//            新增,可以多个号码,过滤已经存在表里的号码
            $hasInData = [];
            foreach ($this->model->whereIn('number', $numbers)->select(['number'])->cursor() as $row) {
                $hasInData[] = $row->number;
            }
            $numbers = array_diff($numbers, $hasInData);
            $inArray = [];
            foreach ($numbers as $k => $number) {
                $number = trim($number);
                $inData['number'] = $number;
                $area = $PhoneArea->find($inData['number']);
                $inData['province'] = $area['province'] ?? '';
                $inData['city'] = $area['city'] ?? '';
                $inData['operator'] = $this->getOperatorName($inData['number'], $operatorType, $operatorFlag);
                $groupNumberEnd8[] = substr($number, 3);
                // 加价设置
                $prices = $this->getIncPrice($inData['raw_price'], $incPriceSetting);
                $inData['sale_price'] = $prices['sale_price'];
                $inData['agent_price'] = $prices['agent_price'];
                $inArray[] = array_merge($inData, $this->splitNumber($inData['number']));
            }
            if (!empty($inArray)) {
                $this->model->insert($inArray);
            }
        }
        $this->setEnd8GroupCode($groupNumberEnd8);
        return $this->returnMsg(200, '数据操作完成');
    }

//设置尾8相同的号码组编号
    public function setEnd8GroupCode($groupNumberEnd8 = [])
    {
        if (!empty($groupNumberEnd8)) {
            //        整个表找尾8相同的
            $rawWhere = 'RIGHT(number,8) in(' . implode(',', $groupNumberEnd8) . ')';
            if (count($groupNumberEnd8) == 1) {
                $rawWhere = 'RIGHT(number,8) ="' . $groupNumberEnd8[0] . '"';
            }
            $tmpData = [];
            foreach ($this->model->whereRaw($rawWhere)->select(['id', 'number'])->cursor() as $row) {
                $n8 = substr($row->number, 3);
                if (isset($tmpData[$n8])) {
                    $oldRow = $tmpData[$n8][0];
                    if ($oldRow['number'] != $row->number) {
                        $groupCode = md5($oldRow['id'] . $oldRow['number'] . $row->id . $row->number);
                        $this->model->whereRaw('id="' . $oldRow['id'] . '" OR id="' . $row->id . '"')->update(['group_code' => $groupCode]);
                    }
                } else {
                    $tmpData[$n8][] = $row;
                }
            }
            unset($tmpData);
        }
    }

//加价格,是根据底价范围来加的
    public function getIncPrice($rawPrice, $incPriceSetting = null)
    {
        if (empty($incPriceSetting)) {
            $ModelDictConfig = new DictConfig();
            $incPriceSetting = $ModelDictConfig->getValue('xhPriceInc');
        }
        // 找出价格区间
        $incItem = [
            'inc' => 0,
            'agentInc' => 0
        ];
        if (isset($incPriceSetting['open']) && intval($incPriceSetting['open']) === 1) {
            foreach ($incPriceSetting['items'] as $k => $item) {
                if ($rawPrice >= $item['min'] && $rawPrice <= $item['max']) {
                    $incItem = $item;
                    break;
                }
            }
        }
        return [
            'sale_price' => $rawPrice + intval($incItem['inc']),
            'agent_price' => $rawPrice + intval($incItem['agentInc']),
        ];
    }

    public function getOperatorName($number, $operatorType = [], $operatorFlag = [])
    {
        if (empty($operatorType)) {
            $operatorType = config('card.operatorType');
        }
        if (empty($operatorFlag)) {
            $operatorFlag = config('card.operatorFlag');
        }
        $flag = substr(trim($number), 0, 3);
        $type = -1;
        foreach ($operatorFlag as $k => $items) {
            if (in_array($flag, $items)) {
                $type = $k;
                break;
            }
        }
        return $operatorType[$type] ?? '';
    }

//    导入号码
    public function importPhones($id)
    {
        // 查询出来上传的文件
        $ModelMoreFile = new OrderMoreModel();
        $moreFileData = $ModelMoreFile->where(['id' => $id, 'is_run' => 0, 'type' => 'addXhNumber'])->first();
        if (!$moreFileData) {
            return $this->returnMsg(1, '未查询到文件');
        }
        $shopId = $moreFileData->shop_id;
        $upFile = $moreFileData->upload_rout;
        $upFile = public_path($upFile);
        if (empty($upFile) || !file_exists($upFile)) {
            return $this->returnMsg(100, '文件不存在:' . $upFile);
        }
        if (empty($shopId)) {
            return $this->returnMsg(103, '店铺id 不存在');
        }
        $createdUserId = $moreFileData->created_by;
//        加价设置
        $ModelDictConfig = new DictConfig();
        $incPriceSetting = $ModelDictConfig->getValue('xhPriceInc');
        $operatorType = config('card.operatorType');
        $operatorFlag = config('card.operatorFlag');
        $excelClient = new Excel();

        $importData = $excelClient->importFile($upFile, ['goods_id', 'number', 'raw_price', 'booking', 'is_pretty', 'is_top'], function ($data) use ($createdUserId, $shopId, $incPriceSetting, $operatorType, $operatorFlag) {
            $data['shop_id'] = $shopId;
            $data['sale'] = 0;
            $data['booking'] = intval($data['booking']);
            $data['goods_id'] = intval($data['goods_id']);
            $data['number'] = trim($data['number']);
//            $data['province'] = trim($data['province']);
//            $data['city'] = trim($data['city']);
            $data['is_pretty'] = intval($data['is_pretty']);
            $data['is_top'] = intval($data['is_top']);
            $data['created_by'] = $createdUserId;
            $data['raw_price'] = floatval($data['raw_price']);
            //运营商
            $data['operator'] = $this->getOperatorName($data['number'], $operatorType, $operatorFlag);
            // 加价格
            $prices = $this->getIncPrice($data['raw_price'], $incPriceSetting);
            $data['sale_price'] = $prices['sale_price'];
            $data['agent_price'] = $prices['agent_price'];
            return array_merge($data, $this->splitNumber($data['number']));
        });
        if (!empty($importData['data'])) {
            $successNum = 0;
            $failNum = 0;
            $updateNum = 0;
            $PhoneArea = new PhoneArea();
            foreach (array_chunk($importData['data'], 500, true) as $key => $rows) {
                $phoneArray = [];
                $groupNumberEnd8 = [];
                foreach ($rows as $k => $row) {
                    $area = $PhoneArea->find($row['number']);
                    $rows[$k]['province'] = $area['province'] ?? '';
                    $rows[$k]['city'] = $area['city'] ?? '';
                    $phoneArray[] = $row['number'];
                    // 设置尾8相同的号码成组编号
                    $groupNumberEnd8[] = substr($row['number'], 3);
                }
                if (!empty($groupNumberEnd8)) {
                    $this->setEnd8GroupCode($groupNumberEnd8);
                }
                // 已经存在的号码
                $phoneArray = array_unique($phoneArray);
                $where = [];
                $where['in']['number'] = $phoneArray;
                $oldNumbers = [];
                foreach ($this->model->searchWhere($where)->select(['number'])->cursor() as $oldRow) {
                    $oldNumbers[] = $oldRow->number;
                }
                $newAddData = [];
                foreach ($rows as $row) {
                    if (in_array($row['number'], $oldNumbers)) {
                        //更新
                        $updateNum += 1;
                        $this->model->where(['number' => $row['number']])->update($row);
                    } else {
                        $newAddData[] = $row;
                    }
                }
                if ($this->model->insert($newAddData)) {
                    $successNum += count($newAddData);
                } else {
                    $failNum += count($newAddData);
                }

            }
        }
        $ModelMoreFile->where(['id' => $moreFileData['id']])->update(['is_run' => 1, 'fail_num' => $failNum, 'success_num' => $successNum + $updateNum]);
        return $this->returnMsg(200, '文件处理完成');
    }

}
